<template>
<q-layout view="hHh Lpr fFf">
    <!-- Be sure to play with the Layout demo on docs -->

    <!-- (Optional) The Header -->
    <q-header v-if="!isSinglePage" elevated>
        <q-toolbar class="body-dark back-dark shadow-7">
            <q-btn flat round dense :icon="$q.platform.is.mobile ? 'home' : 'list'" @click="handleLeftDrawer" />

            <q-toolbar-title class="desktop-only">{{
          projectinfo.name
        }}</q-toolbar-title>
            <q-space></q-space>
            <div class="row flex-center q-gutter-xs">
                <q-btn flat dense size="14px" icon="people" @click="handleMemberDrawer">
                    <q-badge color="white" v-if="onlineList.length > 0" outline class="q-mb-sm no-border" floating>{{ onlineList.length }}</q-badge>
                </q-btn>
                <q-btn flat size="14px" dense icon="share" @click="isShareDialog = !isShareDialog" />
                <q-btn flat size="14px" padding="xs" icon="message" @click="handleMsgDrawer">
                    <q-badge v-if="applyList[1].length > 0" color="red-6" floating>{{
              applyList[1].length
            }}</q-badge>
                </q-btn>
                <q-btn flat size="14px" dense icon="menu" >
                  <q-menu size="14px" content-class="bg-grey-9 text-white" anchor="bottom right" self="top right" :offset="[0,10]">
                    <q-item v-if="$q.platform.is.electron" dense clickable  @click="handleCreateResolveProject">
                        <q-item-section dense avatar style="min-width:20px" class="q-pa-sm">
                            <q-icon name="mdi-plus"></q-icon>
                        </q-item-section>
                        <q-item-section>创建达芬奇项目</q-item-section>
                    </q-item>


                </q-menu>
                </q-btn>
                <q-separator vertical color="grey-7 q-mx-sm"></q-separator>
                <q-avatar size="30px" v-if="user.avatar">
                    <img :src="user.avatar" />
                    <q-menu v-model="userMenu" content-class="bg-grey-9 text-white" anchor="bottom right" self="top right" :offset="[0, 10]">
                        <q-card flat class="transparent no-border q-py-none">
                            <q-card-section class="row items-center q-py-sm">
                                <q-avatar size="25px" class="q-mr-sm" v-if="user.avatar">
                                    <img :src="user.avatar" />
                                </q-avatar>
                                {{ user.username
                  }}<span :class="user.isQw ? 'text-orange-4' : 'text-green-6'">@{{ user.isQw ? "一方映画" : "微信" }}</span>
                            </q-card-section>
                        </q-card>
                        <q-item dense clickable>
                            <q-item-section @click="handleToUserCenter">个人中心</q-item-section>
                        </q-item>
                        <q-separator inset color="grey-4"></q-separator>
                        <q-item dense clickable @click="handleLogout">
                            <q-item-section>退出登录</q-item-section>
                        </q-item>
                    </q-menu>
                </q-avatar>
            </div>
        </q-toolbar>
    </q-header>

    <!-- (Optional) The Footer -->
    <q-footer v-if="!isSinglePage" elevated :style="$q.platform.is.mobile ? 'height:60px' : 'height:30px'" :class="
        $q.platform.is.mobile
          ? 'back-dark shadow-up-3'
          : 'column back-dark shadow-7'
      ">
        <q-tabs :breakpoint="600" stretch dense align="center" class="mobile-only" active-color="teal-6">
            <q-route-tab style="width: 200px" icon="widgets" :to="'/studio/' + pid" replace label="工作台" />
            <q-route-tab icon="mdi-briefcase-check" :to="'/progress/' + pid" style="width: 200px" replace label="进度" />
            <q-route-tab icon="movie" style="width: 200px" :to="'/works/' + pid" replace label="成品" />
        </q-tabs>

        <q-toolbar class="col-grow desktop-only back-dark shadow-7">
            <q-btn flat round dense icon="menu" size="10px" @click="leftDrawer = !leftDrawer" />
        </q-toolbar>
    </q-footer>

    <!-- (Optional) A Drawer; you can add one more with side="right" or change this one's side -->
    <q-drawer v-if="!isSinglePage" v-model="leftDrawer" side="left" style="z-index: 1" :width="250" :breakpoint="200" class="no-scroll mobile-hide desktop-only" content-class="bg-dark ">
        <!-- QScrollArea is optional -->
        <!-- <q-scroll-area class="fit q-pa-sm">

      </q-scroll-area> -->
        <q-scroll-area style="height: calc(100% - 130px); margin-top: 130px">
            <q-separator class="q-ma-sm" color="grey-7" />
            <q-list class="text-primary">
                <q-item clickable :to="'/studio/' + pid" v-ripple active-class="my-menu-link">
                    <q-item-section avatar>
                        <q-icon name="widgets" />
                    </q-item-section>
                    <q-item-section>工作台</q-item-section>
                </q-item>

                <q-separator />
                <q-item clickable v-ripple :to="'/progress/' + pid" active-class="my-menu-link">
                    <q-item-section avatar>
                        <q-icon name="mdi-briefcase-check" />
                    </q-item-section>

                    <q-item-section>进度</q-item-section>
                </q-item>

                <q-separator />
                <q-item clickable v-ripple :to="'/works/' + pid" active-class="my-menu-link">
                    <q-item-section avatar>
                        <q-icon name="movie" />
                    </q-item-section>

                    <q-item-section>成品</q-item-section>
                </q-item>

                <q-separator />
                <q-separator class="q-ma-sm" color="grey-7" />
                <q-item clickable :to="'/'" v-ripple class="text-primary">
                    <q-item-section avatar>
                        <q-icon name="home" />
                    </q-item-section>

                    <q-item-section>返回项目首页</q-item-section>
                </q-item>
            </q-list>
        </q-scroll-area>
        <q-img class="absolute-top" img-class="my-custom-image" src="~assets/icons/material.png" style="height: 130px">
            <div class="bg-transparent">
                <q-img class="q-mb-sm" src="~assets/icons/一方映画logo200708竖版亮色.png" width="200px" contain />
                <div class="text-weight-bold text-h6">项目工作间</div>
                <div>项目编号：{{ pid }}</div>
            </div>
        </q-img>
    </q-drawer>
    <q-dialog v-if="!isSinglePage" v-model="isShareDialog" :position="$q.platform.is.mobile ? 'bottom' : 'standard'">
        <q-card style="width: 50%" class="back-dark">
            <q-card-section class="column items-start">
                <div class="row full-width justify-between">
                    <div class="column items-start">
                        <div class="text-h6">分享项目</div>
                        <div class="text-subtitle1">
                            企业内外成员{{ sharePermission.name }}
                            <span v-if="user.right >= 3" @click="isPermissionDialog=!isPermissionDialog" class="text-blue non-selectable">修改权限</span>
                        </div>
                    </div>
                    <q-btn flat icon="close" @click="isShareDialog = !isShareDialog">
                    </q-btn>
                </div>

                <q-separator color="grey"></q-separator>
            </q-card-section>
            <q-card-section class="q-pb-xl q-gutter-sm">
                <q-btn stack>
                    <q-icon size="35px" name="link" color="teal-6" @click="handleShareLink"></q-icon>复制链接
                </q-btn>
                <q-btn stack>
                    <q-icon size="35px" name="mdi-qrcode" color="blue-6"></q-icon>生成二维码
                </q-btn>
            </q-card-section>
        </q-card>
        <q-dialog v-model="isPermissionDialog" :full-width="$q.platform.is.mobile">
            <q-card style="width: 50%" class="back-dark">
                <q-card-section class="column items-start">
                    <div class="row full-width justify-between">
                        <div class="column items-start">
                            <div class="text-h6">权限设置</div>

                        </div>
                        <q-btn flat icon="close" @click="isPermissionDialog = !isPermissionDialog">
                        </q-btn>
                    </div>

                    <q-separator color="grey-2"></q-separator>
                </q-card-section>
                <q-card-section>
                    <q-select filled dark v-model="sharePermission" :options="permissionOptions" option-label="name" option-value="val" label="权限设置" />
                </q-card-section>
                <q-card-actions align="right" class="q-pb-xl q-gutter-sm ">
                    <q-btn @click="isPermissionDialog = !isPermissionDialog" outline label="确认">

                    </q-btn>

                </q-card-actions>
            </q-card>
        </q-dialog>
    </q-dialog>

    <member-drawer v-if="!isSinglePage" :memberList="memberList" :onlineList="onlineList" :pid="pid" :user="user" :isMemberDrawer="isMemberDrawer" @update="handleReload" @close="handleMemberDrawer('close')"></member-drawer>

    <msg-drawer v-if="!isSinglePage" :applyList="applyList" :pid="pid" :isMsgDrwer="isMsgDrwer" :user="user" @update="handleReload" @close="handleMsgDrawer('close')"></msg-drawer>

    <q-page-container @click="isMemberDrawer, (isMsgDrwer = false)" class="back-dark">
        <router-view :projectinfo="projectinfo" :user="user" @isSingle="handleSinglePage" @reload="handleReload" />
    </q-page-container>
</q-layout>
</template>

<script>
import {
    date
} from "quasar";
import {
    getProjectinfo,
    generateProjectShareLink,
    checkShareCode
} from "assets/api/studio";

import {
    checkMember,
    loadApplys,
    updateApplyInfo,
    deleteApplyInfo,
} from "assets/api/member";

import {
    copyToClipboard
} from 'quasar'

export default {
    name: "StudioLayout",
    components: {
        MemberList: () => import("components/MemberList.vue"),
        MsgDrawer: () => import("components/studio/MsgDrawer.vue"),
        MemberDrawer: () => import("components/studio/MemberDrawer.vue"),
    },

    data() {
        return {
            leftDrawer: true,
            isMemberDialog: false,
            isMemberDrawer: false,
            pid: "",
            projectinfo: {},
            stime: "",
            etime: "",
            completetime: "",
            user: {
                right: 0,
                isQw: false,
            },
            memberList: [],
            onlineList: [],
            rawMemberList: [],
            applyList: [
                [],
                [],
                []
            ],
            isShareDialog: false,
            userMenu: false,
            isMsgDrwer: false,
            waitList: [],
            isSinglePage: false,
            isPermissionDialog: false,
            permissionOptions: [{
                name: "默认加入可查看",
                val: 1,
            }, {
                name: "默认加入可编辑",
                val: 3,
            }, ],
            sharePermission: {
                name: "默认加入可查看",
                val: 1,
            },

        };
    },
    created() {
      document.title="一方映画"


        this.pid = this.$route.params.pid;
        this.loadUserInfo();

        //有scode 就检查权限
        //分享链接加入项目
        if (this.$route.query.scode) {
            this.checkPermission();
        } else {
            //没有就核查是否是文档成员
            this.handleCheckMember();
        }

        if (this.$q.platform.is.mobile) {
            this.leftDrawer = false;
        }
    },
    mounted() {

        this.handleSockets();


        // this.$q.fullscreen.request()
    },
    beforeDestroy() {
        // this.$q.fullscreen.exit()
        this.$storage.removeItem(this.pid);
        this.$socket.disconnect();
        this.$q.loading.hide()
    },
    methods: {
      handleCreateResolveProject(){
        console.log('createProject');
        this.$q.electron.ipcRenderer.send('createProject',this.projectinfo)
      },
        handleShareLink() {
            generateProjectShareLink({
                pid: this.pid,
                permission: this.sharePermission.val
            }).then(res => {
                console.log(res);
                if (res.data.code == 1) {
                    let url = 'https://oa.yfyh.cc/studio/' + this.pid + '?scode=' + res.data.scode
                    let msg = `一方映画邀请您加入项目《${this.projectinfo.project_id}${this.projectinfo.name}》\n链接：${url}\n`;
                    this.$copyText(msg)
                        .then(() => {
                            this.$message.success('复制链接成功！')
                        })
                        .catch(() => {
                            this.$message.error('复制链接失败！')
                        })
                } else {
                    this.$message.error('生成分享链接失败！')
                }
            })
        },
        handleSinglePage(val) {
            this.isSinglePage = val;
        },
        handleSockets() {
            this.$socket.io.opts.auth = {
                    token: JSON.parse(window.localStorage.getItem("user")).token,
                },
                this.$socket.connect();
            this.$socket.on("online_users", (data) => {
                console.log(data, "online-users");
                let projectUser = []
                data.forEach(item => {
                    if (item.pid == this.pid) {
                        projectUser.push(item)
                    }
                })
                this.onlineList = projectUser;
            });
            this.$socket.on("isReload_project", (data) => {

                this.handleCheckMember();
            });
            this.$socket.on("isReload_apply", (data) => {
                this.handleLoadApplys();

            });
        },
        handleReload(loadType) {
            if (loadType == "project") {
                this.$socket.emit("reload_project");
                this.loadprojectinfo();
            }
            if (loadType == "apply") {
                this.$socket.emit("reload_apply");
                console.log('reload_applys');
                this.handleLoadApplys();
            }

        },
        handleCloseMsgDrawer() {
            this.isMsgDrwer = false;
        },
        checkPermission() {
            let scode = this.$route.query.scode;
            console.log(scode);
            checkShareCode({
                pid: this.pid,
                scode: scode
            }).then(res => {
                if (res.data.code = 1) {
                    this.loadprojectinfo();
                    this.handleLoadApplys();
                }
            })
        },
        handleCheckMember() {
            let reqData = {
                pid: this.pid,
            };
            checkMember(reqData).then((res) => {

                if (res.data.code == 1) {
                    this.loadprojectinfo();
                    this.handleLoadApplys();
                    this.$q.loadingBar.stop();

                } else {
                    console.log("here");
                    this.$router.replace("/member/" + this.pid);
                }
            });
        },
        loadUserInfo() {
            let userinfo = this.$storage.getItem("userinfo");
            if (userinfo) {
                this.user = userinfo;
            }
        },
        handleSortMember(memberlist) {
            /** 两个参数： 参数1 是排序用的字段， 参数2 是：是否升序排序 true 为升序，false为降序*/
            function compare(attr, rev) {
                // console.log(attr, rev)
                if (rev == undefined) {
                    rev = 1;
                } else {
                    rev = rev ? 1 : -1;
                }
                return (a, b) => {
                    a = a[attr];
                    b = b[attr];
                    if (a < b) {
                        return rev * -1;
                    }
                    if (a > b) {
                        return rev * 1;
                    }
                    return 0;
                };
            }
            let newMemberList = memberlist.sort(compare("permission", false));

            newMemberList.forEach((item) => {
                if (item.openid != undefined && item.openid.length > 0) {
                    //微信用户
                    item.username = item.nickname;
                    item.isQw = false;
                }
                if (item.eid != undefined && item.eid > 0) {
                    //企微用户
                    item.isQw = true;
                }
            });
            // let sortedMemberList = [];
            // sortedMemberList.push(newMemberList);
            // sortedMemberList.push(qw);
            // sortedMemberList.push(wechat);

            return newMemberList;
        },
        formatProjectData(projectinfo) {

            let curtime = new Date().getTime();
            let stime = parseInt(projectinfo.stime);
            let etime = parseInt(projectinfo.etime);
            if (projectinfo.rank == 0) {
                projectinfo.color = "pink-6";
            } else if (projectinfo.rank == 1) {
                projectinfo.color = "teal-6";
            } else if (projectinfo.rank == 2) {
                projectinfo.color = "yellow-8";
            } else if (projectinfo.rank == 3) {
                projectinfo.color = "blue-6";
            }
            if (stime > curtime) {
                projectinfo.progress = 0;
            } else if (etime < curtime) {
                projectinfo.progress = 100;
            } else {
                projectinfo.progress = parseFloat(
                    (((curtime - stime) / (etime - stime)) * 100).toFixed(1)
                );
            }
            projectinfo.stime = date.formatDate(stime, "YYYY/MM/DD");
            projectinfo.etime = date.formatDate(etime, "YYYY/MM/DD");

            return projectinfo

        },

        loadprojectinfo() {
            let reqdata = {
                pid: this.pid,
            };
            getProjectinfo(reqdata).then((res) => {

                console.log(res.data.data[0]);

                if (res.data.data[0].length > 0) {
                    let memberlist = res.data.data[1].concat(res.data.data[2]);

                    let newMemberlist = this.handleSortMember(memberlist);

                    this.memberList = newMemberlist;
                    this.rawMemberList = newMemberlist;
                    this.handleUserRight(memberlist);

                    let projectinfo = this.formatProjectData(res.data.data[0][0]);
                    projectinfo.memberList = newMemberlist;

                    this.$storage.setItem(this.pid,projectinfo)
                    this.$store.commit("setProjectinfo", projectinfo);
                    this.projectinfo = projectinfo;
                    this.projectinfo.memberList = newMemberlist;

                    document.title = this.projectinfo.name;
                    this.user.pid = this.pid
                    this.$socket.emit("join", this.user);

                    if (this.$platform.inMiniProgram()) {
                        wx.miniProgram.postMessage({
                            data: {
                                projectinfo: projectinfo,
                                stime: this.stime,
                                etime: this.etime,
                            },
                        });
                    }
                    if (projectinfo.completetime) {
                        this.completetime = projectinfo.completetime;
                    }
                } else {
                    this.$router.replace("/404");
                }
            });
        },
        //设置用户权利
        handleUserRight(memberList) {
            let user = this.user;
            //permission 用户项目权限（1-仅查看；2-可上传；3-可编辑；4-管理员；5-创建者）
            memberList.forEach((item) => {
                if (user.openid != undefined && user.openid.length > 0) {
                    //微信用户
                    if (item.openid == user.openid) {
                        this.user.right = item.permission;
                        this.user.permission = item.permission;
                        this.user.isQw = false;
                    }
                }
                if (user.eid != undefined && user.eid > 0) {
                    //企微用户
                    if (item.eid == user.eid) {
                        this.user.right = item.permission;
                        this.user.permission = item.permission;
                        this.user.isQw = true;
                    }
                }
            });
            this.$store.commit('setUser',this.user)
        },
        handleLeftDrawer() {
            if (this.$q.platform.is.mobile) {
                this.$router.replace("/");
            } else {
                this.leftDrawer = !this.leftDrawer;
            }
        },
        handleMemberDrawer(v) {
            if (v == "close") {
                this.isMemberDrawer = false;
            } else {
                if (this.isMsgDrwer) {
                    this.isMsgDrwer = false;
                }
                this.isMemberDrawer = !this.isMemberDrawer;
            }
        },
        handleMsgDrawer(v) {
            if (v == "close") {
                this.isMsgDrwer = false;
            } else {
                if (this.isMemberDrawer) {
                    this.isMemberDrawer = false;
                }
                this.isMsgDrwer = !this.isMsgDrwer;
            }
        },
        handleLoadApplys() {
            loadApplys({
                pid: this.pid,
            }).then((res) => {
                let rawData = res.data.data;
                if (rawData.length > 0) {
                    let data = [];
                    rawData.forEach(item => {
                        let index = data.findIndex(i => i.apply_id == item.apply_id);

                        if (index == -1) {
                            data.push(item)
                        }
                    })
                    console.log(data, 'newdata')

                    function sordApplys(data) {
                        let sortedList = [];
                        let waitList = [];
                        let doneList = [];
                        data.forEach((item) => {
                            if (item.status == 1) {
                                waitList.push(item);
                            } else {
                                doneList.push(item);
                            }
                        });
                        sortedList.push(data);
                        sortedList.push(waitList);
                        sortedList.push(doneList);
                        return sortedList;
                    }

                    this.applyList = sordApplys(data);

                } else {
                    this.applyList = [
                        [],
                        [],
                        []
                    ]
                }

            });
        },
        handleToUserCenter() {
            this.$router.push("/user");
        },
        handleLogout() {
            this.$q
                .dialog({
                    title: "提示",
                    message: "确认退出登录吗？",
                    cancel: true,
                    persistent: true,
                })
                .onOk(() => {
                    this.$storage.removeItem("user");
                    this.$storage.removeItem("userinfo");
                    this.$router.push("/login");
                    this.$q.notify({
                        color: "light-green-4",
                        icon: "far fa-check-circle",
                        position: "top",
                        textColor: "white",
                        message: "退出成功！",
                        timeout: "1500",
                    });
                })
                .onOk(() => {
                    // console.log('>>>> second OK catcher')
                })
                .onCancel(() => {})
                .onDismiss(() => {
                    // console.log('I am triggered on both OK and Cancel')
                });
        },
    },
};
</script>
